package com.cci.kangdao.service.impl;


import com.cci.kangdao.dao.CompanyHasEngineTypeTDao;
import com.cci.kangdao.dao.CompanyTDao;
import com.cci.kangdao.dao.EngineTypeTDao;
import com.cci.kangdao.dao.ServiceStationDao;
import com.cci.kangdao.dao.model.CompanyHasEngineTypeT;
import com.cci.kangdao.dao.model.CompanyT;
import com.cci.kangdao.dto.request.SyncNpbuEngineTypeToEAppRequest;
import com.cci.kangdao.service.EngineTypeService;
import com.cci.kangdao.utilTool.*;

import com.gexin.fastjson.JSON;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("EngineTypeService")
public class EngineTypeServiceImpl implements EngineTypeService {

    private Logger log = Logger.getLogger(this.getClass().getName());

    @Autowired
    private ServiceStationDao serviceStationDao;
    @Resource
    private EngineTypeTDao engineTypeTDao;
    @Resource
    private CompanyTDao companyTDao;
    @Resource
    private CompanyHasEngineTypeTDao companyHasEngineTypeTDao;

    @Override
    public ModelAndView getEngineTypeList(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
       
        String keyword = MapUtils.getString(map, "keyword");
        
        List<Map<String, Object>> engineTypeList = serviceStationDao.getEngineTypeOrderByTypeName(keyword);
      
        JSONObject obj = new JSONObject();
        try {
            JSONObject jb = new JSONObject();
            jb.put("engineTypeList", engineTypeList);
            obj.put("status", SMSEnum.type0.getIndex());
            obj.put("msg", SMSEnum.type0.getName());
            obj.put("data", jb);
            //返回客户
            ParameterTool.writeResponse(response, obj.toString());
            obj = null;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            // TODO: handle exception
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }


    @Override
    public ModelAndView syncNpbuEngineTypeToEApp(String paramStr, HttpServletRequest request,
                                                 HttpServletResponse response) {
        log.info("syncNpbuEngineTypeToEApp.aspx接口入参paramStr："+paramStr);
        JSONObject obj = new JSONObject();
        //响应的data数据
        Map<String,Object> returnMap = new HashMap<>();
        //1.提取参数信息
        SyncNpbuEngineTypeToEAppRequest syncNpbuEngineTypeToEAppRequest = JSON.parseObject(paramStr, SyncNpbuEngineTypeToEAppRequest.class);
        //2.校验参数是否必填
        Integer flag = syncNpbuEngineTypeToEAppRequest.getFlag();
        String oldEngineType = syncNpbuEngineTypeToEAppRequest.getOldEngineType();
        String newEngineType = syncNpbuEngineTypeToEAppRequest.getNewEngineType();
        if(flag == -1 || (flag != 1 && flag != 2) || StringUtils.isEmpty(newEngineType) || (flag == 2 && StringUtils.isEmpty(oldEngineType))){
            ParameterTool.writeResponse(response, 17,"缺少必要参数或所传参数非枚举值！");
            return null;
        }
        try {
            obj.put("status", 0);
            obj.put("msg", "success");
            com.alibaba.fastjson.JSONObject newEngineTypeJsonObject = com.alibaba.fastjson.JSON.parseObject(newEngineType);
            com.alibaba.fastjson.JSONObject oldEngineTypeJsonObject = new com.alibaba.fastjson.JSONObject();
            // "{\"displacement\":\"45345\",\"engintypesys\":\"54534\",\"productType\":\"656\",\"remak\":\"345343\",\"typename\":\"53543\"}"
            Map<String,Object> engineTypeMap = new HashMap<>();
            if(flag == 1){   //新增时通过新机型json里的信息进行查询数据库是否存在
                engineTypeMap.put("engintypesys",newEngineTypeJsonObject.getString("engintypesys"));
                engineTypeMap.put("typename",newEngineTypeJsonObject.getString("typename"));
            }else{       //修改时通过旧机型json里的信息进行查询数据库是否存在
                oldEngineTypeJsonObject = com.alibaba.fastjson.JSON.parseObject(oldEngineType);
                engineTypeMap.put("engintypesys",oldEngineTypeJsonObject.getString("engintypesys"));
                engineTypeMap.put("typename",oldEngineTypeJsonObject.getString("typename"));
            }
            engineTypeMap.put("displacement",newEngineTypeJsonObject.getString("displacement"));
            engineTypeMap.put("remak",newEngineTypeJsonObject.getString("remak"));
            Map<String,Object> verifyMap = engineTypeTDao.verify(engineTypeMap);
            if(flag == 1){   //新增逻辑
                if(MapUtils.isNotEmpty(verifyMap)){   //存在则直接把当前机型的主键id返给npbu系统
                    log.info("npbu当前新增的机型在e路康明斯系统存在");
                    returnMap.put("eAppEngineTypeId",MapUtils.getLongValue(verifyMap,"ID"));
                    obj.put("data",returnMap);
                    ParameterTool.writeResponse(response, obj.toString());
                    return null;
                }
                int num = engineTypeTDao.insert(engineTypeMap);   //不存在则新增
                log.info("npbu机型维护成功");
                if(num > 0){
                    Long engineTypeId = MapUtils.getLongValue(engineTypeMap,"id",-1);
                    returnMap.put("eAppEngineTypeId",engineTypeId);
                    //自动维护企业和机型关系   通过编号反查npbu的企业信息
                    CompanyT companyT = companyTDao.getCompanyInfoByCompanyNo("NPSH");
                    CompanyHasEngineTypeT engineTypeT = new CompanyHasEngineTypeT();
                    engineTypeT.setCompanyid(companyT.getId());
                    engineTypeT.setEnginetypeid(engineTypeId);
                    companyHasEngineTypeTDao.insertSelective(engineTypeT);
                    log.info("npbu企业与机型关系维护成功");
                }
                obj.put("data",returnMap);
                ParameterTool.writeResponse(response, obj.toString());
                return null;
            }

            if(MapUtils.isNotEmpty(verifyMap)){
                engineTypeMap.put("engintypesys",newEngineTypeJsonObject.getString("engintypesys"));
                engineTypeMap.put("typename",newEngineTypeJsonObject.getString("typename"));
                engineTypeMap.put("id",MapUtils.getLongValue(verifyMap,"ID"));
                engineTypeTDao.updateByPrimaryKey(engineTypeMap);
                returnMap.put("eAppEngineTypeId",MapUtils.getLongValue(verifyMap,"ID"));
            }
            obj.put("data",returnMap);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            String msg = "{\"status\": -99,\"msg\": \"未知错误\"}";
            ParameterTool.writeResponse(response, msg);
        }
        ParameterTool.writeResponse(response, obj.toString());
        return null;
    }

}
